<?php

//include dirname(__FILE__).'/libsys_oracle.php';
//LDAP认证
$ldap_ip = '210.28.96.66';
$ldap_port = 389;
$user="2004100367";
$passwd="2004100367";
$rs=false;

$ldap_user = "uid=".$user.",ou=People,dc=niit,dc=edu,dc=cn";
$ldap_password = $passwd;

$ldapConnect=@ldap_connect($ldap_ip , $ldap_port );
ldap_set_option($ldapConnect, LDAP_OPT_PROTOCOL_VERSION,3);
//建立到ldap服务器的连接LDAP_SERVER_IP是ldap服务器ip，LDAP_SERVER_PORT是ldap服务器端口(默认389)
//$bind=true;
$bind=@ldap_bind($ldapConnect , $ldap_user ,$ldap_password);
//验证帐号密码，ldap_bind第一个为绑定的连接，第二个为用户名(注意是否有后缀)，第三个为密码。

if($bind )  {
  //验证成功
    $rs =  "+OK\n"  ;

} else {
  //验证失败
    $rs = "+FALSE\n"  ;
}
echo $rs;


if($bind ) 
        {//验证成功 
              echo "LDAP bind successful...<br /><br />";
                  $SEARCH_DN= 'ou=People,dc=niit,dc=edu,dc=cn'; 
                  //搜索基本条件值(类似于数据库的库和表) 
                  $SEARCH_FIELDS= array('sn', 'cn', 'uid','memberof'); 
                  //需要的搜索结果 
                  $result= ldap_search($ldapConnect,$SEARCH_DN,"uid=" . $user); 
                  //第三个参数是限定搜索结果为用户名为$user(类似where后的搜索条件)           
                  $retData = ldap_get_entries($ldapConnect, $result); 
                  echo "sum:".$retData["count"];;
                  var_dump($retData);

                  
                  foreach($retData as $k => $v) 
                  {//筛选整理数据，返回 
                           ( array( 
                                    'userName'=> $v['cn'][0], 
                                    'nickName'=> $v['uid'][0] ,
                                    'memberof'=> $v['memberof'][0] 
                           ));  
                           $regex = '#^cn=([^,]*),#';
                           $str= $v['memberof'][0];
                           $memberof = "";
                           //$matches = array();
                           if(preg_match($regex, $str, $matches)){
							    //var_dump($matches);
							    $memberof = $matches[1]."|".$matches[0];
							    //echo $memberof;
							}
							//echo $memberof;
                  }   
                  
        }  

ldap_close($ldapConnect);
//关闭ldap连接
die();
?>